using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vms.Web.Models;
using Vms.Web.Lib;

namespace Vms.Web.Controllers
{   
    public class ScreensController : Controller
    {
        private VmsWebContext context = new VmsWebContext();
        private List<SelectListItem> controlType;
        private List<SelectListItem> handleLight;
        private List<SelectListItem> adjustType;
        
        private List<SelectListItem> hours, minutes;

        #region CONTRUCTOR

        public ScreensController()
        {
            controlType = new List<SelectListItem>();
            for (int i = 0; i < Utility.ControlerType.GetLength(0); ++i )
            {
                SelectListItem item = new SelectListItem();
                item.Text = (string)Utility.ControlerType[i, 0];      // Name of controller type
                item.Value = ""+Utility.ControlerType[i, 1];     // Value of controller type
                controlType.Add(item);
            }

            adjustType = new List<SelectListItem>();
            for (int i = 0; i < Utility.ADJUST_TYPE.GetLength(0); ++i ) 
            {
                SelectListItem item = new SelectListItem();
                item.Text = (string)Utility.ADJUST_TYPE[i,0];
                item.Value = "" + Utility.ADJUST_TYPE[i, 1];
                adjustType.Add(item);
            }


                handleLight = new List<SelectListItem>();
            for (int i = 1; i <= 16; i++)
            {
                SelectListItem item = new SelectListItem();
                item.Text = i.ToString();
                item.Value = i.ToString();
                handleLight.Add(item);
            }

            hours = new List<SelectListItem>();
            for (int i = 0; i < 24; i++)
            {
                SelectListItem item = new SelectListItem();
               
                item.Text = i<10? "0" + i.ToString() : i.ToString() ;
                item.Value = i.ToString();
                hours.Add(item);
            }

            minutes = new List<SelectListItem>();
            for (int i = 0; i < 60; i++)
            {
                SelectListItem item = new SelectListItem();
                item.Text = i < 10 ? "0" + i.ToString() : i.ToString();
                item.Value = i.ToString();
                minutes.Add(item);
            }
        }


        #endregion

        #region SCREENS

        //---------------------------------------------------------------------------
        //
        // GET: /SCREENs/

        public ViewResult Index()
        {
            return View(context.SCREENS.Include(screen => screen.PROGRAMS).Include(screen => screen.SCREEN_LOGS).ToList());
        }

        //
        // GET: /SCREENs/Details/5

        public ViewResult Details(int id)
        {
            SCREEN screen = context.SCREENS.Single(x => x.Id == id);
            return View(screen);
        }

        //
        // GET: /SCREENs/Create

        public ActionResult Create()
        {
            ViewBag.ControllerType = controlType;       // List of controller type
            return View();
        }

        public PartialViewResult CreateScreen()
        {
            ViewBag.ControllerType = controlType;       // List of controller type
            return PartialView("CreateScreen");
        }

        //
        // POST: /SCREENs/Create

        [HttpPost]
        public ActionResult Create(SCREEN screen)
        {
            if (ModelState.IsValid)
            {
                SCREEN_BRIGHTNESS scr_brightness = new SCREEN_BRIGHTNESS();
                
                Vms.Web.Models.PROGRAM program = new PROGRAM();
                program.Name = "program1";
                SCREEN_STATUS scr_status = new SCREEN_STATUS();
                context.SCREEN_STATUS.Add(scr_status);
                // Create screen status file
                string screenStatusFile = screen.Name+".ini";
                System.IO.File.CreateText(Utility.pathScreenStatus+screenStatusFile);
                screen.ScreenStatusFile = screenStatusFile;
                screen.ScreenStatus = scr_status;
                screen.ScreenBrightness = scr_brightness;
                // Create Content
                CONTENT_IMG contentImg = new CONTENT_IMG();
                contentImg.Img_Height = contentImg.Img_Width = contentImg.Img_x = contentImg.Img_y = 0;
               
                CONTENT_TXT contentTxt = new CONTENT_TXT();
                contentTxt.Txt_Height = contentTxt.Txt_Width = contentTxt.Txt_x = contentTxt.Txt_y = 0;
                contentTxt.FontSize = 14;

                string file = "txt_" + DateTime.Now.Ticks + ".txt";
                System.IO.File.CreateText(Utility.PathScreenContentTxt + file);
                contentTxt.TxtFileName = file;

                CONTENT content = new CONTENT();
                content.CONTENT_IMG.Add(contentImg);
                content.CONTENT_TXT.Add(contentTxt);
                program.CONTENTS.Add(content);

                screen.PROGRAMS.Add(program);
                context.SCREENS.Add(screen);
                context.SaveChanges();

                JsonResult result = Json(screen);
                result.ContentType = "text/plain";
               // return result;
            }
            return RedirectToAction("Index");
        }

        //
        // GET: /SCREENs/Edit/5

        public ActionResult Edit(int id)
        {
            SCREEN screen = context.SCREENS.Single(x => x.Id == id);
            ViewBag.ControllerType = controlType;   // List of controller type
            ViewBag.statusId = screen.ScreenStatus_Id;
            return View(screen);
        }

        public ActionResult EditScreen(int screenId)
        {
            SCREEN screen = context.SCREENS.Single(x => x.Id == screenId);
            JsonResult result = Json(screen);
            result.ContentType = "text/plain";
            return result;
        }

        //
        // POST: /SCREENs/Edit/5

        [HttpPost]
        public ActionResult Edit(SCREEN screen)
        {
            if (ModelState.IsValid)
            {
                context.Entry(screen).State = EntityState.Modified;
                context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(screen);
        }

        //
        // GET: /SCREENs/Delete/5

        public ActionResult Delete(int id)
        {
            SCREEN screen = context.SCREENS.Single(x => x.Id == id);
            context.SCREENS.Remove(screen);
            context.SaveChanges();
           // return View(screen);
            return RedirectToAction("Index");
        }

        //
        // POST: /SCREENs/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            SCREEN screen = context.SCREENS.Single(x => x.Id == id);
            PROGRAM p = context.PROGRAMS.Single(c => c.Screen_id == id);
            CONTENT con = context.CONTENTS.Single( cont => cont.PROGRAM.Id == p.Id);
            CONTENT_IMG img = context.CONTENT_IMG.Single( im => im.CONTENT.Id == con.Id);
            CONTENT_TXT txt = context.CONTENT_TXT.Single(t => t.CONTENT.Id == con.Id );
            // Delete Screen Status file
            string screenStatusFile = Utility.pathScreenStatus + screen.ScreenStatusFile;
            if (System.IO.File.Exists(screenStatusFile))
                System.IO.File.Delete(screenStatusFile);
            context.CONTENT_TXT.Remove(txt);
            context.CONTENT_IMG.Remove(img);
            context.CONTENTS.Remove(con);
            context.PROGRAMS.Remove(p) ;
            context.SCREENS.Remove(screen);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        #endregion

        #region BRIGHTNESS CONTROL
        /// <summary>
        /// edit brightness 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult EditBrightness(int id)
        {
            ViewBag.handleLight = handleLight;
            ViewBag.adjustType = adjustType;
            ViewBag.hours = hours;
            ViewBag.minutes = minutes;
            
            SCREEN    screen = context.SCREENS.Single(b => b.ScreenBrightness_Id == id);
            ViewBag.screen_name = screen.Name;
           return View(context.SCREEN_BRIGHTNESS.Single(br =>br.Id == id));
        }

        [HttpPost]
        public ActionResult EditBrightness(SCREEN_BRIGHTNESS screenBrightness)
        {
            if (ModelState.IsValid)
            {
                context.Entry(screenBrightness).State = EntityState.Modified;
             
                // Apply for all.
               // = false;
                bool isChecked = Boolean.Parse(Request.Form.GetValues("ApplyForAll")[0]);

                if (isChecked == true)
                {
                    ApplyForAll(screenBrightness);
                }
            

                string s = (Request.Params["ApplyForAll"].First().ToString()); 
            
                context.SaveChanges();
                return RedirectToAction("BrightnessControl");
            }
            return View(screenBrightness);
        }


        /// <summary>
        /// view all screens with brightness
        /// </summary>
        /// <returns></returns>
        public ViewResult BrightnessControl()
        {
            List<SCREEN> screens = context.SCREENS.ToList();
            return View(screens);
        }
        /// <summary>
        /// display brightness control for a screen
        /// </summary>
        /// <param name="id">id of the screen</param>
        /// <returns></returns>

        public ViewResult ScreenBrightness(int id)
        {
            SCREEN scr = context.SCREENS.Single(s => s.Id == id);
            return View(context.SCREEN_BRIGHTNESS.Where(screenBrightness => screenBrightness.Id == scr.ScreenBrightness_Id).ToList());
        }
        /// <summary>
        /// apply brightness adjustment for all screens
        /// </summary>
        /// <returns></returns>
        /// 
        public void ApplyForAll(SCREEN_BRIGHTNESS screenBrightness)
        {
            if (ModelState.IsValid)
            {
                List<SCREEN_BRIGHTNESS> br = context.SCREEN_BRIGHTNESS.ToList();

                foreach (var item in br)
                {
                    context.Entry(item).State = EntityState.Modified;

                    item.nAdjustType = screenBrightness.nAdjustType;
                    item.nHandleLight = screenBrightness.nHandleLight;
                    item.nHour1 = screenBrightness.nHour1;
                    item.nHour2 = screenBrightness.nHour3;
                    item.nHour3 = screenBrightness.nHour3;
                    item.nHour4 = screenBrightness.nHour4;
                    item.nLight1 = screenBrightness.nLight1;
                    item.nLight2 = screenBrightness.nLight2;
                    item.nLight3 = screenBrightness.nLight3;
                    item.nLight4 = screenBrightness.nLight4;
                    item.nMinute1 = screenBrightness.nMinute1;
                    item.nMinute2 = screenBrightness.nMinute2;
                    item.nMinute3 = screenBrightness.nMinute3;
                    item.nMinute4 = screenBrightness.nMinute4;
                    
                 //   context.SaveChanges();
                }
            }
           
        }
        #endregion

        #region PROGRAMS_STATUS

        public ViewResult Programs(int id)
        {
            return View(context.PROGRAMS.Where(program => program.SCREEN.Id == id).ToList());
        }

        public ViewResult ScreenStatus(int id)
        {
            return View(context.SCREEN_STATUS.Where(scr_status => scr_status.Id == id).ToList());
        }

        #endregion

        protected override void Dispose(bool disposing)
        {
            if (disposing) {
                context.Dispose();
            }
            base.Dispose(disposing);
        }
    }

   
}